<template>
  <view class="stack-item" :style="itemStyle">
    <slot></slot>
  </view>
</template>

<script lang="ts" setup>
import { computed, inject } from 'vue'

interface Props {
  top?: string | number
  right?: string | number
  bottom?: string | number
  left?: string | number
  width?: string | number
  height?: string | number
}

const props = defineProps<Props>()

const stackAlignment = inject('stackAlignment', 'topLeft') as Alignment

type Alignment =
  | 'topLeft'
  | 'topCenter'
  | 'topRight'
  | 'centerLeft'
  | 'center'
  | 'centerRight'
  | 'bottomLeft'
  | 'bottomCenter'
  | 'bottomRight'

const itemStyle = computed(() => ({
  position: 'absolute',
  top: typeof props.top === 'number' ? `${props.top}rpx` : props.top,
  right: typeof props.right === 'number' ? `${props.right}rpx` : props.right,
  bottom: typeof props.bottom === 'number' ? `${props.bottom}rpx` : props.bottom,
  left: typeof props.left === 'number' ? `${props.left}rpx` : props.left,
  width: typeof props.width === 'number' ? `${props.width}rpx` : props.width,
  height: typeof props.height === 'number' ? `${props.height}rpx` : props.height,
  ...getPositioning(stackAlignment),
}))

function getPositioning(alignment: Alignment) {
  switch (alignment) {
    case 'topLeft':
      return { top: '0', left: '0' }
    case 'topCenter':
      return { top: '0', left: '50%', transform: 'translateX(-50%)' }
    case 'topRight':
      return { top: '0', right: '0' }
    case 'centerLeft':
      return { top: '50%', left: '0', transform: 'translateY(-50%)' }
    case 'center':
      return { top: '50%', left: '50%', transform: 'translate(-50%, -50%)' }
    case 'centerRight':
      return { top: '50%', right: '0', transform: 'translateY(-50%)' }
    case 'bottomLeft':
      return { bottom: '0', left: '0' }
    case 'bottomCenter':
      return { bottom: '0', left: '50%', transform: 'translateX(-50%)' }
    case 'bottomRight':
      return { bottom: '0', right: '0' }
    default:
      return {}
  }
}
</script>
